package com.lychee.moli.interceptor;

import com.lychee.moli.entity.IdentityEntity;
import com.lychee.moli.outher.IConstant;
import com.lychee.moli.utils.TokenUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Lychee on 2018/4/11 13:53.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */
public class TokenInterceptor implements HandlerInterceptor {


    private Logger logger = Logger.getLogger(TokenInterceptor.class);


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader(IConstant.TOKEN);
        if (header != null && header.length() > 0) {
            IdentityEntity identityEntity = null;
            try {
                identityEntity = TokenUtils.parseTokenMessage(header, TokenUtils.SECRET_KEY);
                //{token='null', userId='43', issuer='null', userName='null', duration=1523423744000}
                if (identityEntity.getUserId() != null) {
                    logger.info("身份校验正确" + identityEntity.toString());
                    request.setAttribute("UserID", identityEntity);
                    return true;
                } else {
                    logger.info("身份校验错误");
                }
            } catch (ExpiredJwtException e) {
                logger.trace("过期");
                return false;
            } catch (UnsupportedJwtException e) {
                logger.trace("不支持该JWT");
                return false;
            } catch (MalformedJwtException e) {
                logger.trace("不支持该JWT 格式");
                return false;
            } catch (SignatureException e) {
                logger.trace("签名错误");
                return false;
            } catch (IllegalArgumentException e) {
                logger.trace("参数异常");
                return false;
            }
        }
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
